package servlet.soft;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import dao.SoftDao;
import dbutil.DBHelper;
import entity.Software;

public class AddSoftServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2523748811429250352L;

	public AddSoftServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		JSONObject jsonObject = new JSONObject();
		String softName = request.getParameter("softName");
		String actMode = request.getParameter("actMode");
		String status = request.getParameter("status");
		String category = request.getParameter("category");
		String kmsServer = request.getParameter("kmsServer");
		String keySeg = request.getParameter("keySeg");
		String desc = request.getParameter("desc");
		SoftDao softDao = null;
		Connection conn = null;
		Software software = null;

		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			softDao = new SoftDao();
			
			software = new Software();
			software.setSoftName(softName);
		    software.setSoftDesc(desc);
		    software.setNumLicense(0);
		    software.setAssignedLicense(0);
		    software.setActMode(actMode);
		    software.setStatus(status);
		    software.setCategory(category);
		    software.setDepartLicense(0);
		    software.setKmsServer(kmsServer);
		    software.setUserLicense(0);
		    software.setUsedLicense(0);
		    software.setCreateDate(new Date());
		    software.setKeySeg(keySeg);
			
		   boolean isSuccess = softDao.addSoftDownload(software);
		   if(isSuccess) {
				jsonObject.put("retCode", "1");
				conn.commit();
			} else {
				jsonObject.put("retCode", "0");
				jsonObject.put("desc", "AddSoftServlet dao");
				conn.rollback();
			}
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "AddSoftServlet Exception");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}
		
	}

	public void init() throws ServletException {
	}

}
